Lesson 6 -Logical operators

Logical operators will only work on boolean values and , apart from not, will require two values. This means that it is common to mix comparison operators with logical ones. However it is possible to directly specify truth and to cast other data types into boolean. 0 is considered false while every other number is true. Also text is considered true unless it contains no text! Below are some examples.


print True and False # false
print 2 > 4 or 5 == 5 # true
print bool(0) and True # false
print bool(23) and True # true
print bool("") and True # false
print bool("hi") and True # true


Logical operators are case sensitive so it is important to always specify them in lower case. True and False both start with capital letters. The next example shows how and can be used in a real world context. Notice the use of capital letters.


# a simple printer example. trayEmpty represents if there is paper in the tray
# hasItems shows if there are items to print
trayEmpty = True
hasItems = True

if hasItems == True and trayEmpty == True:
	print "you need to add paper"
elif hasItems == True and trayEmpty == False:
	print "printing ... "
else:
	print "waiting for print jobs"


Finally if a variable is a boolean you do not have to specify == True. The final example shows how this can be used to make the code more readable. not is used to show that printing can only occur if there is paper, that is the paper tray is not empty.


# a simple printer example. trayEmpty represents if there is paper in the tray
# hasItems shows if there are items to print
trayEmpty = True
hasItems = True

if hasItems and trayEmpty:
	print "you need to add paper"
elif hasItems and (not trayEmpty):
	print "printing ... "
else:
	print "waiting for print jobs"


key learning points